package com.le.tester.imooc.oldfairy;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * createTime：2021/8/26 16:34
 * description：LSemaphore
 */
public class LSemaphore extends AbstractQueuedSynchronizer {

    public LSemaphore(int permits) {
        setState(permits);
    }

    @Override
    protected int tryAcquireShared(int arg) {
        int state = getState();
        if (state == 0) {
            return -1;
        }
        int left = state - 1;
        if (compareAndSetState(state, left)) {
            return left;
        }
        return -1;
    }

    @Override
    protected boolean tryReleaseShared(int arg) {
        int state = getState();
        return compareAndSetState(state, state + 1);
    }
}
